﻿using System;
using System.Collections.Generic;

namespace Batman.SQLScripts
{
    public class CommonDataSelect
    {
        /// <summary>
        /// 根据条件获取到脚本
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static List<string> GetCommands(Dictionary<string, object> param)
        {
            #region 1、判断条件及相关初始化

            if (param == null || !param.ContainsKey("key"))
            {
                throw new ArgumentException("参数key没有传入");
            }

            var strKey = param["key"].ToString().Trim();
            Mapping mapping = SQLScript.GetMapping(strKey);

            if (mapping == null)
            {
                throw new ArgumentException($"参数[key]={strKey}没有找到配置项");
            }

            // 获取分页参数
            //GetPagination(param, out var skip, out var size);

            #endregion

            List<string> commandTexts = new List<string>();

            #region 2、脚本where处理

            foreach (var schema in mapping.Schemas)
            {
                var strWhere = string.Empty;
                foreach (var schemaItem in schema.Items)
                {
                    if (!param.ContainsKey(schemaItem.Name)) continue;

                    strWhere = $"{strWhere} and t.{schemaItem.Name}=?{schemaItem.Name}";
                }

                var commandText = schema.Command.Text;
                if (strWhere != string.Empty)
                {
                    commandText = $"SELECT t.* FROM ({commandText}) t WHERE 1=1 {strWhere}";
                }
                commandTexts.Add(commandText);
            }


            #endregion

            return commandTexts;
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="param"></param>
        private static void GetPagination(Dictionary<string, string> param, out int skip, out int size)
        {
            skip = 0;
            size = 10;

            if (param.ContainsKey("skip"))
            {
                int.TryParse(param["skip"].Trim(), out skip);
            }

            if (param.ContainsKey("size"))
            {
                int.TryParse(param["size"].Trim(), out size);
            }
        }
    }
}
